package com.dlwx.firefighting.activity;

import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.support.v7.widget.LinearLayoutManager;
import android.view.View;
import android.webkit.WebView;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.dlwx.firefighting.R;
import com.dlwx.firefighting.adapter.VideoDetailAdapter;
import com.dlwx.firefighting.bean.CommentBean;
import com.dlwx.firefighting.bean.VideoBean;
import com.dlwx.firefighting.config.Constant;
import com.dlwx.firefighting.utils.DialogUtils;
import com.dlwx.firefighting.utils.SPUtils;
import com.dlwx.firefighting.utils.ToastUtils;
import com.github.jdsjlzx.ItemDecoration.DividerDecoration;
import com.github.jdsjlzx.interfaces.OnItemClickListener;
import com.github.jdsjlzx.interfaces.OnLoadMoreListener;
import com.github.jdsjlzx.recyclerview.LRecyclerView;
import com.github.jdsjlzx.recyclerview.LRecyclerViewAdapter;
import com.github.jdsjlzx.view.CommonHeader;
import com.lzy.okgo.OkGo;
import com.lzy.okgo.callback.StringCallback;
import com.lzy.okgo.model.Response;
import com.shuyu.gsyvideoplayer.video.StandardGSYVideoPlayer;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class VideoDetailActivity extends BaseActivity {

    @BindView(R.id.title_left_one_btn)
    ImageView titleLeftOneBtn;
    @BindView(R.id.tv_middle_title)
    TextView tvMiddleTitle;
    @BindView(R.id.video_detail_recyclerview)
    LRecyclerView recyclerview;
    private VideoDetailAdapter videoAdapter;
    private List<CommentBean> datas = new ArrayList<>();
    private LRecyclerViewAdapter lRecyclerViewAdapter;
    private StandardGSYVideoPlayer player;
    private String videoId;
    private String userId;
    private TextView desc_tv;
    private int page=1;
    private int requestNum=10;
    private int count=0;
    private String thumbUrl;
    private String videoUrl;
    private WebView webView;
    private  com.tencent.smtt.sdk.WebView qqWeb;
    private TextView nameTv;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_video_detail);
        ButterKnife.bind(this);
        videoId=getIntent().getStringExtra("id");
        userId= (String)SPUtils.get(this, Constant.USER_ID,"");
        getDatas();
        initView();
    }

    @Override
    protected void onResume() {
        super.onResume();
        videoAdapter.clear();
        page=1;
        getCommentDatas();
    }

    private void getCommentDatas() {
        OkGo.<String>post(Constant.COMMENT_LIST)
                .tag(this)
             /*   （1、首页banner 2、商城banner3、学习中心banner）*/
//        0、商品 2、视频
                .params("id_value",videoId)
                .params("user_id",userId)
                .params("num",10)
                .params("page",page)
                .params("type",2)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
//                        DealResult result=new DealResult();
//                        List<CommentBean> beans=result.dealComment(VideoDetailActivity.this,response,new TypeToken<BaseBean<CommentBean>>(){}.getType());
//
//                        videoAdapter.addAll(beans);
//                        recyclerview.refreshComplete(requestNum);
//                        count=videoAdapter.getItemCount();
                    }
                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtils.toastForShort(VideoDetailActivity.this,getString(R.string.bad_net));
                    }
                });
    }

    private void getDatas() {
        OkGo.<String>post(Constant.VIDEO_INFO)
                .tag(this)
                .params("user_id",userId)
                .params("video_id",videoId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
//                        DealResult result=new DealResult();
//                        List<VideoBean> beans=result.deal(VideoDetailActivity.this,response,new TypeToken<BaseBean<VideoBean>>(){}.getType());
//                        setDatas(beans);
                    }
                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtils.toastForShort(VideoDetailActivity.this,getString(R.string.bad_net));
                    }
                });
    }

    private void setDatas(List<VideoBean> beans) {
        if (beans.isEmpty()) {
            return;
        }
        VideoBean bean = beans.get(0);
        nameTv.setText(bean.getVideo_name());
        ImageView imageView = new ImageView(this);
        thumbUrl=bean.getVideo_thumb();
        Glide.with(getApplicationContext()).load(thumbUrl).into(imageView);
        imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
        player.setThumbImageView(imageView);
        if (bean.is_collect()) {
            likeTv.setCompoundDrawables(likeDrawable, null, null, null);
        }else{
            likeTv.setCompoundDrawables(unlikeDrawable, null, null, null);
        }
        videoUrl=bean.getVideo_url();
        qqWeb.getSettings().setJavaScriptEnabled(true);// 支持js
        qqWeb.getSettings().setUseWideViewPort(true); //自适应屏幕
//        qqWeb.getSettings().setLayoutAlgorithm(com.tencent.smtt.sdk.WebSettings.LayoutAlgorithm.SINGLE_COLUMN);
        qqWeb.setWebChromeClient(new com.tencent.smtt.sdk.WebChromeClient());
        qqWeb.setWebViewClient(new com.tencent.smtt.sdk.WebViewClient(){

            @Override
            public boolean shouldOverrideUrlLoading(com.tencent.smtt.sdk.WebView webView, String s) {
                return false;
            }
        });
        qqWeb.loadUrl(videoUrl);
    }
    Drawable likeDrawable;
    Drawable unlikeDrawable;
    int likeWith,likeHeight;
    public void initView() {
        if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP) {
            unlikeDrawable=getDrawable(R.mipmap.like_unselect);
            likeDrawable=getDrawable(R.mipmap.like);
        }else{
            unlikeDrawable=getResources().getDrawable(R.mipmap.like_unselect);
            likeDrawable=getResources().getDrawable(R.mipmap.like);
        }
        likeWith=likeDrawable.getIntrinsicWidth();
        likeHeight=likeDrawable.getIntrinsicHeight();
        likeDrawable.setBounds(0, 0, likeWith, likeHeight);
        unlikeDrawable.setBounds(0, 0, likeWith, likeHeight);
//
        tvMiddleTitle.setText("学习详情");
        titleLeftOneBtn.setVisibility(View.VISIBLE);
        videoAdapter = new VideoDetailAdapter(this);
        recyclerview.setLayoutManager(new LinearLayoutManager(this));
        videoAdapter.setDataList(datas);
        lRecyclerViewAdapter = new LRecyclerViewAdapter(videoAdapter);
        recyclerview.setAdapter(lRecyclerViewAdapter);
        recyclerview.setPullRefreshEnabled(true);
        DividerDecoration divider = new DividerDecoration.Builder(this)
                .setHeight(R.dimen.divider_height)
                .setPadding(R.dimen.divider_padding)
                .setColorResource(R.color.line_gray)
                .build();
        recyclerview.addItemDecoration(divider);
        initHeader();
        recyclerview.setLoadMoreEnabled(true);
        recyclerview.setPullRefreshEnabled(false);
       /* //设置下拉刷新
        mainRecyclerview.setOnRefreshListener(new OnRefreshListener() {
            @Override
            public void onRefresh() {
                page = 1;
                adapter.clear();
                lRecyclerViewAdapter.notifyDataSetChanged();
            }
        });*/
        recyclerview.refresh();
        //设置上拉加载更多
        recyclerview.setOnLoadMoreListener(new OnLoadMoreListener() {
            @Override
            public void onLoadMore() {
                if (count < (page * requestNum)) {
                    ToastUtils.toastForShort(VideoDetailActivity.this, getString(R.string.no_more));
                    recyclerview.setNoMore(true);
                } else {
                    page++;
                    getCommentDatas();
                }
            }
        });
        lRecyclerViewAdapter.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(View view, int position) {
//                startActivity(new Intent(getActivity(), GoodsDetailsActivity.class));
            }
        });

    }

    TextView likeTv;
    RelativeLayout webRl;
    //创建header
    private void initHeader() {
        CommonHeader header = new CommonHeader(this, R.layout.groupon_videodetail_header);
//        webView= (WebView) header.findViewById(R.id.webView);
        qqWeb= (com.tencent.smtt.sdk.WebView) header.findViewById(R.id.qqweb);
        webRl= (RelativeLayout) header.findViewById(R.id.web_rl);
        likeTv= (TextView) header.findViewById(R.id.like_tv);
        desc_tv= (TextView) header.findViewById(R.id.desc_tv);
        nameTv= (TextView) header.findViewById(R.id.name_tv);
        final ImageView toFullImg = (ImageView) header.findViewById(R.id.tofull_img);
        player = (StandardGSYVideoPlayer) header.findViewById(R.id.video_player);
        TextView commentTv = (TextView) header.findViewById(R.id.comment_tv);
        commentTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i=new Intent(VideoDetailActivity.this, CommentActivity.class);
                i.putExtra("url",thumbUrl);
                i.putExtra("id",videoId);
                i.putExtra("comment_type",2);
                startActivity(i);
            }
        });

        toFullImg.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i=new Intent(VideoDetailActivity.this, WebActivity.class);
                i.putExtra("url",videoUrl);
                startActivity(i);
            }
        });

        likeTv.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                collectVideo();
            }
        });

        lRecyclerViewAdapter.addHeaderView(header);
    }

    private void collectVideo() {
        DialogUtils.showProgressDlg(this,"");
        OkGo.<String>post(Constant.COLLECT_VIDEO)
                .params("user_id",userId)
                .params("video_id",videoId)
                .execute(new StringCallback() {
                    @Override
                    public void onSuccess(Response<String> response) {
                        DialogUtils.stopProgressDlg();
//                        DealResult dealResult=new DealResult();
//                        List<StatusBean> beans=dealResult.deal(VideoDetailActivity.this,response,new TypeToken<BaseBean<StatusBean>>(){}.getType());
//                        if(beans.isEmpty()){
//                            return;
//                        }
//                        int type=beans.get(0).getType();
//                        if(type==1){
//                            likeTv.setCompoundDrawables(likeDrawable, null, null, null);
//                            ToastUtils.toastForShort(VideoDetailActivity.this,"收藏成功！");
//                        }else if(type==2){
//                            likeTv.setCompoundDrawables(unlikeDrawable, null, null, null);
//                            ToastUtils.toastForShort(VideoDetailActivity.this,"取消收藏成功！");
//                        }
                    }

                    @Override
                    public void onError(Response<String> response) {
                        super.onError(response);
                        ToastUtils.toastForShort(VideoDetailActivity.this,getString(R.string.bad_net));
                        DialogUtils.stopProgressDlg();
                    }
                });
    }


    @OnClick({R.id.title_left_one_btn, R.id.tv_middle_title})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.title_left_one_btn:
                VideoDetailActivity.this.finish();
                break;
            case R.id.tv_middle_title:
                break;
        }
    }

    @Override
    public void onBackPressed() {
        if(player.isIfCurrentIsFullscreen()){
            player.onBackFullscreen();

        }else {
            player.release();
            super.onBackPressed();
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        qqWeb.destroy();

    }

    public void refreshData(int position,boolean isZan,String zanNum){
        CommentBean bean = videoAdapter.getDataList().get(position);
        bean.setIs_zan(isZan);
        bean.setZan(zanNum);
        videoAdapter.getDataList().set(position,bean);
        lRecyclerViewAdapter.notifyItemChanged(lRecyclerViewAdapter.getAdapterPosition(false,position) , "jdsjlzx");
        lRecyclerViewAdapter.notifyDataSetChanged();
    }
}
